import java.lang.reflect.Field;

/**
 * 反射方法
 * @author zhu_shuai
 * @since 8/4
 */
public class Demo02Field {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        // 反射创建对象
        User user = User.class.newInstance();
        // 反射获取属性
        System.out.println("--------------所有属性----------------");
        Field[] declaredFields = User.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            // 设置访问权限
            declaredField.setAccessible(true);
            Class<?> type = declaredField.getType();
            if (declaredField.getType() != null) {
                // 属性赋值
                if (String.class.equals(type)) {
                    declaredField.set(user, "张三");
                }else if (int.class.equals(type)) {
                    declaredField.set(user, 20);
                }
            }
            System.out.printf("name: %s, type: %s %n", declaredField.getName(), declaredField.getType());
        }
        System.out.println(user.toString());

    }
}
